package br.gov.ibama.server.auth;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.log4j.Logger;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;

public class CustomAuthenticationProvider implements AuthenticationProvider {
	private Logger log = Logger.getLogger(CustomAuthenticationProvider.class);
	private String dbHost;
	private String dbPort;
	private String dbName;

	private static final String MENSAGEM_ERRO = "CPF e/ou Senha incorretos";

	public Authentication authenticate(Authentication authentication) {
		String username = (String)authentication.getPrincipal();
		String password = (String)authentication.getCredentials();
		
		boolean resultado = this.verificaUsuario(username, password);

		// Caso não tenha autenticado no banco lança uma exceção
		if (!resultado) {
			throw new BadCredentialsException(MENSAGEM_ERRO);
		}

		Authentication customAuthentication = 
				new CustomUserAuthentication("ROLE_USER", authentication);
		
		customAuthentication.setAuthenticated(true);
		return customAuthentication;
	}

	/**
	 * Verifica se o usuário do oracle com as credenciais passadas são válidos.
	 * @param usuario
	 * @param senha
	 * @return
	 */
	private boolean verificaUsuario(String usuario, String senha) {
		System.out.println("teste");
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException cnfe) {
			log.fatal(cnfe.getMessage());
			System.exit(1);
		}
		Connection connection = null;
		try {
			String url = "jdbc:mysql://localhost/sigeol?user=root&password=admin";
			connection = 
					DriverManager.getConnection(url);

			if (connection != null) {
				connection.close();
				return true;
			}
		} catch (SQLException e) {
			
		}

		return false;
	}

	public boolean supports(Class<? extends Object> authentication) {
		return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
	}

	public String getDbHost() {
		return dbHost;
	}

	public void setDbHost(String dbHost) {
		this.dbHost = dbHost;
	}

	public String getDbPort() {
		return dbPort;
	}

	public void setDbPort(String dbPort) {
		this.dbPort = dbPort;
	}

	public String getDbName() {
		return dbName;
	}

	public void setDbName(String dbName) {
		this.dbName = dbName;
	}
	
	

}